<template>
  <cloud-dialog
    :visible="visible"
    :title="title"
    :width="480"
    :mask-closable="false"
    :before-ok="handleSubmit"
    :before-open="handleBeforeOpen"
    :before-close="handleBeforeClose">
    <a-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      layout="vertical">
      <a-form-item
        class="mb-0!"
        field="name"
        label="分组名称"
        hide-asterisk
        asterisk-position="end"
        required>
        <a-input
          v-model="formData.name"
          :max-length="20"
          placeholder="请输入分组名称">
        </a-input>
      </a-form-item>
    </a-form>
  </cloud-dialog>
</template>
<script lang="ts" setup>
import type { SiteGroupItem } from '@/apis/model/site'
import {
  addApiSiteGroupApi,
  updateApiSiteGroupByIdApi
} from '@/apis/modules/site/siteGroup'
import { type FieldRule, type FormInstance } from '@arco-design/web-vue'
interface IProps {
  record?: SiteGroupItem
  visible: boolean
}
const props = withDefaults(defineProps<IProps>(), {
  visible: false
})
interface IEmits {
  (e: 'update:visible', value: boolean): void
  (e: 'refresh'): void
}
const emits = defineEmits<IEmits>()
const title = computed(() => (props.record?.id ? '编辑分组' : '添加分组'))
const formRef = ref<FormInstance>()
const formData = ref({
  name: ''
})
const formRules = computed<{ [key: string]: FieldRule[] }>(() => {
  return {
    name: [
      {
        required: true,
        message: '请输入分组名称'
      }
    ]
  }
})
const handleBeforeOpen = async () => {
  if (props.record) {
    formData.value.name = props?.record.name
  }
}
const handleBeforeClose = async () => {
  await formRef.value?.resetFields()
  emits('update:visible', false)
}
async function handleSubmit() {
  const error = await formRef.value?.validate()
  if (error) return false
  const apiPath = props.record.id
    ? updateApiSiteGroupByIdApi
    : addApiSiteGroupApi
  // 提交表单
  const data = { ...formData.value }
  await apiPath({ ...data, id: props.record?.id ?? undefined })
  ToastUtils.success(props.record?.id ? '修改成功' : '添加成功')
  emits('update:visible', false)
  emits('refresh')
}
</script>

<style lang="less" scoped></style>
